#include <stdio.h>
#include "Database.h"

#ifdef _WIN32
#ifdef _DEBUG
   #include <crtdbg.h>
   #undef THIS_FILE
   static char THIS_FILE[] = __FILE__;
   #define new       new( _NORMAL_BLOCK, __FILE__, __LINE__)
   #define malloc(s) _malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__)
#endif
#endif

// Constructor
Database::Database(char *username, char *password, char *db, char *host, int port) {
	if(mysql_init(&conn) == NULL) {
		printf("Failed to initate MySQL connection.\n");
		exit(1);
	}

	if(!mysql_real_connect(&conn, host, username, password, db, port, NULL, 0)) {
		printf("Failed to connect to %s, (%s).\n", host, mysql_error(&conn));
		exit(1);
	}

	if(!mysql_thread_safe()) {
		fprintf(stderr, "Not Thread safe!!!");
		exit(1);
	}
//	else {
//		printf("MySQL is thread safe.\n");
//	}
}

// Deconstructor
Database::~Database(void) {
	// cleanly close the database socket
	mysql_close(&conn);
}

// query the data base
int Database::query(char *query) {
	return mysql_query(&conn, query);
}

// initiate thread-safe mysql call
MYSQL_RES* Database::threadsafe_query(HANDLE mutex, char *query) {
	MYSQL_RES *result = NULL;

	// -- Thread-Safe Mysql call --
	// Request ownership of mutex
	WaitForSingleObject(mutex, INFINITE);
	// Make mysql calls which need Mutex protection
	mysql_query(&(conn), query);
	result = mysql_store_result(&(conn));
	// Release the mutex
	ReleaseMutex(mutex);

	return result;
}

void Database::safe_mysql_free_result(MYSQL_RES *result) {
	if(result != NULL) {
		mysql_free_result(result);
	}
}